import React, { JSX } from 'react';
import { NulCommonOperations, NulDialog, NulFormItem } from '../../components/NulDialog';
import { MenuItem, Select, TextField, Typography } from '@mui/material';
import { UserEntry, updateUser } from '../../actions/UserManagement';
import { useAppDispatch } from '../../actions/hooks';
import { defaultAuthority } from '../../util/TextTransform';

interface UpdateUserDialogProps {
  open: boolean;
  onClose: () => void;
  userEntry?: UserEntry;
};

function UpdateUserDialog(props: UpdateUserDialogProps): JSX.Element {
  const { open, onClose, userEntry } = props;

  const dispatch = useAppDispatch();

  const [name, setName] = React.useState<string>('');
  const [authority, setAuthority] = React.useState<string>(defaultAuthority);

  React.useEffect(() => {
    if (userEntry !== undefined) {
      setName(userEntry.userName);
      setAuthority(userEntry.authority);
    }
  }, [userEntry]);

  const onConfirmClicked = () => {
    if (userEntry !== undefined) {
      dispatch(updateUser({ id: userEntry.id, userName: name, authority: authority }));
    }
    onClose();
  };

  const onCancelClicked = () => {
    onClose();
  };

  return (
    <NulDialog
      open={open}
      onClose={onClose}
      title='Update User'
      operations={
        <NulCommonOperations
          onPositiveClicked={onConfirmClicked}
          onNegativeClicked={onCancelClicked}
        />
      }
    >
      <NulFormItem hint='UID' necessary={false} component={
        <Typography fontFamily='Inter'>{userEntry?.id}</Typography>
      } />
      <NulFormItem hint='Name' component={
        <TextField
          placeholder='User Name'
          fullWidth size='small'
          value={name}
          onChange={(event) => { setName(event.target.value); }}
        />
      } />
      <NulFormItem hint='Authority' component={
        <Select
          value={authority}
          onChange={(event) => { setAuthority(event.target.value); }}
          fullWidth size='small'
          defaultValue={defaultAuthority}
        >
          <MenuItem value='admin'>Administrator</MenuItem>
          <MenuItem value='user'>User</MenuItem>
        </Select>
      } />
    </NulDialog>
  );
}

export { UpdateUserDialog };